import React, { useEffect, useState } from 'react';
import Web3 from 'web3';
import { Card, Button, message } from 'antd';
import { useParams } from 'react-router-dom';
import MarketplaceABI from '../contract/ABIs/Marketplace.json';
import MaterialListAddr from '../contract/ADDRESSes/MaterialListAddr';
import './SellerProducts.css';

const SellerProducts = () => {
    const { userAddr } = useParams();
    const [web3, setWeb3] = useState(null);
    const [marketplaceContract, setMarketplaceContract] = useState(null);
    const [products, setProducts] = useState([]);

    useEffect(() => {
        const initWeb3 = async () => {
            if (window.ethereum) {
                await window.ethereum.enable();
                const web3Instance = new Web3(window.ethereum);
                setWeb3(web3Instance);
                const marketplaceInstance = new web3Instance.eth.Contract(
                    MarketplaceABI,
                    MaterialListAddr
                );
                setMarketplaceContract(marketplaceInstance);
                console.log('setMarketplaceContract实例化成功', marketplaceInstance);
            }
        };

        initWeb3();
    }, []);

    // 分离出来，让他监视marketplaceContract的变化
    useEffect(() => {
        if (web3 && marketplaceContract) {
            loadSellerProducts(marketplaceContract);
        }
    }, [marketplaceContract]);

    const loadSellerProducts = async (marketplaceInstance) => {
        try {
            const accounts = await web3.eth.getAccounts(); // 现在可以安全地使用 web3 对象
            const productIds = await marketplaceInstance.methods
                .getSellerProductIds()
                .call({ from: accounts[0] });
            const productsData = await Promise.all(
                productIds.map(async (productId) => {
                    const product = await marketplaceInstance.methods
                        .viewProductReports(productId)
                        .call();
                    console.log('product: ', product);
                    return product;
                })
            );
            setProducts(productsData);
        } catch (error) {
            console.error('Failed to load products', error);
        }
    };

    const handleRemoveProduct = async (productId) => {
        try {
            const accounts = await web3.eth.requestAccounts();
            await marketplaceContract.methods
                .removeProduct(productId)
                .send({ from: accounts[0] });
            message.success('商品下架成功');
            loadSellerProducts(marketplaceContract); // Reload the products list
        } catch (error) {
            console.error('Failed to remove product', error);
            message.error('商品下架失败');
        }
    };

    return (
        <div className="seller-products-container">
            <h2>我的商品</h2>
            {web3 && marketplaceContract ? ( // 使用 web3 和 marketplaceContract 是否存在的条件渲染
                <div className="products-grid">
                    {products.map((product) => (
                        <Card key={product[0]} className="product-card">
                            <img
                                src={`https://ipfs.infura.io/ipfs/${product[6]}`}
                                alt={product[2]}
                                className="product-image"
                            />
                            <div className="product-details"></div>
                            <h3>{product[2]}</h3>
                            <p>价格: {Number(product[4])} </p>
                            <p>数量: {Number(product[5])}</p>
                            <p>描述: {product[3]}</p>
                            <p>分类: {product[9]}</p>
                            {/* 根据 product[8] 的值判断显示哪个按钮 */}
                            {product[8] ? ( // product[8] 为 true 时，显示 "下架" 按钮
                                <Button
                                    style={{
                                        backgroundColor: 'pink',
                                        border: 'none',
                                        padding: '10px 20px',
                                        fontSize: '16px',
                                        borderRadius: '5px',
                                        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',
                                        cursor: 'pointer',
                                        transition: 'background-color 0.3s ease',
                                    }}
                                    type="danger"
                                    onClick={() => handleRemoveProduct(product[0])}
                                >
                                    下架
                                </Button>
                            ) : (
                                <Button type="danger" disabled
                                    style={{
                                        backgroundColor: 'pink',
                                        border: 'none',
                                        padding: '10px 20px',
                                        fontSize: '16px',
                                        borderRadius: '5px',
                                        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',
                                        cursor: 'pointer',
                                        transition: 'background-color 0.3s ease',
                                    }}>
                                    已下架
                                </Button>
                            )}

                        </Card>
                    ))}
                </div>
            ) : (
                <p>加载中...</p>
            )}
        </div>
    );
};

export default SellerProducts;